package com.mall.common.validation;

import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.mall.common.bean.WebErrors;
import com.mall.common.plugin.AutoRegisterPlugin;
import com.mall.common.validation.annotation.UrlValidator;
import com.mall.common.validation.annotation.Validations;

public class UrlValidate extends AutoRegisterPlugin implements IValidate  {

	@Override
	public WebErrors validate(HttpServletRequest request, WebErrors errors,
			Validations validations, Map<String, String> decodedUriVariables) {
		UrlValidator[] urls = validations.urls();
		String regex = "[a-zA-z]+://[^\\s]*";
		for(UrlValidator url : urls){
			String fieldName = url.fieldName();
			String value = request.getParameter(fieldName);
			if(StringUtils.isEmpty(value) && decodedUriVariables != null){
				value = decodedUriVariables.get(fieldName);
			}
			if(StringUtils.isEmpty(value) 
					|| !Pattern.matches(regex, value)){
				errors.addErrorString(url.message());
				continue;
			}
		}
		return errors;
	}

	@Override
	public String getType() {
		return "vallidate";
	}

	@Override
	public String getId() {
		return "urlValidate";
	}

	@Override
	public String getName() {
		return "网址格式校验";
	}

	@Override
	public String getVersion() {
		return "1.0.0";
	}

	@Override
	public String getAuthor() {
		return "fangchen";
	}

	@Override
	public void perform(Object... params) {
		
	}

	@Override
	public void register() {
		
	}

}
